package com.zoro.dyformservice.support.web.converter;

import com.zoro.dyformservice.utils.ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;

public class JsonSerializerScannerRegister implements ImportBeanDefinitionRegistrar {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes mapperScanAttrs = AnnotationAttributes
                .fromMap(importingClassMetadata.getAnnotationAttributes(SerializerScan.class.getName()));
        String[] packages;
        if (mapperScanAttrs != null) {
            packages = getPackageArr(mapperScanAttrs);
        } else {
            packages = ClassUtils.defaultPackageArr(importingClassMetadata.getClassName());
        }
        logger.debug("scan package : {}", Arrays.toString(packages));
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(JsonSerializerScanner.class);
        builder.addConstructorArgValue(packages);
        builder.addConstructorArgValue(registry);
        String beanName = importingClassMetadata.getClassName() + "#" + getClass().getSimpleName() + "#" + 0;
        logger.debug("json serializer scanner's bean name is {}", beanName);
        builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        builder.setLazyInit(true);
        registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
    }


    private String[] getPackageArr(AnnotationAttributes attributes) {
        Class<?> baseClass = attributes.getClass("baseClass");
        return ClassUtils.defaultPackageArr(baseClass.getName());

    }
}
